/*
Copyright (C) 2007 Kamal Singh.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

function uiChange()
{
  debug.trace("inside uiChange()" + "  keyboard event code  " + event.keyCode);
  if(event.keyCode == "13")
  {
    debug.trace("user entered ENTER key");
    query = searchBox.value;
    if(query == "")
    {
      searchBox.value = "type something";
      return;
    }
    debug.trace("Search query is   :  " + query);
    changeToDisplayMode();
    makeSoapRequest(query);
  }
}

function changeToDisplayMode()
{
  backgroundImage.src = "clean-red.png";
  searchBox.visible = false;
  searchBoxBackground.visible = false;
  backButton.visible = true;
  displayArea.visible = true;
}

function backButtonHandler()
{
  debug.trace("user entered BACK button");
  backgroundImage.src = "red-urban.png";
  searchBox.visible = true;
  searchBoxBackground.visible = true;
  backButton.visible = false;
  moreButton.visible = false;
  displayArea.visible = false;
  displayArea.removeAllElements();  // Removes and destroys all immediate children of this element.
  noResults.visible = false;
}

var query;
var word, definition, example, url;
var key = "ab438a15fc1a95d1cacc8f04a0f83a1b";
var results = new Array();

function displayResults()
{
  var nItems = results.length;
  for (var i = 0; i < nItems; ++i)
  {
    var r = results[i];
    var item = displayArea.appendElement('<listitem/>');
    var listlabel = item.appendElement('<a vAlign="top" overColor="#FFFFCC" underline="false" trimming="character-ellipsis" color="#C0C0C0" size="9" font="Arial" wordWrap="false" align="left" height="35" width="220"></a>');
    listlabel.innerText = r.definition;
    listlabel.href = r.url;
    listlabel.tooltip = "Word: " + r.word + "\n\nDefinition: " + r.definition + "\n\nExample: " + r.example;
  }
}

function makeSoapRequest(query)
{
  req = new XMLHttpRequest();
  req.open("POST", "http://api.urbandictionary.com/soap", true);
  
    debug.trace("creating the soap request"); 
    var post = '<?xml version="1.0" encoding="UTF-8"?>' +
      '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
      '<soapenv:Body>' +
      '<ns1:lookup soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="urn:UrbanSearch">' +
      '<key xsi:type="xsd:string">' + escape(key) + '</key>' +
      '<term xsi:type="xsd:string">' + escape(query) + '</term>' +
      '</ns1:lookup>' +
      '</soapenv:Body>' +
      '</soapenv:Envelope>';
    req.setRequestHeader('Content-Type', 'text/xml');
    req.send(post);
    debug.trace("soap request sent" + "     " + query);
    req.onreadystatechange = function() {
    
    if (req.readyState == 4)
    {
      if (req.status == 200)
      {
        debug.trace("soap response received"); 
        var doc = new DOMDocument();
        doc.loadXML(req.responseText);
	      var word, definition, example, author, url;
        results = [];
        var elem = doc.getElementsByTagName("item");
        debug.trace("There are " + elem.length + " results");
        if (elem != null && elem.length > 0)
        {
          for (var z = 0; z < elem.length; z++)
          {
            try 
            {
              for (var node = elem[z].firstChild; node != null; node = node.nextSibling)
              {
                if (node.nodeName == "word")
                {
                  try
                  {
                    word = node.firstChild.nodeValue;
                    debug.trace("WORD = " + word);	
                  }
                  catch (err)
                  {
                    word = "";
                    debug.error(err);
                  }
                }
                
                if (node.nodeName == "definition")
                {
                  try
                  {
                    definition = node.firstChild.nodeValue;
                    debug.trace("DEFINATION = " + definition);	
                  }
                  catch (err)
                  {
                    definition = "";
                    debug.error(err);
                  }
                }
                if (node.nodeName == "example")
                {
                  try
                  {
                	  example = node.firstChild.nodeValue;
                    debug.trace("EXAMPLE = " + example);
                  }
                  catch (err)
                  {
                    example = "";
                    debug.error(err);
                  }
                }
                if (node.nodeName == "url")
                {
                  try
                  {
                    url = node.firstChild.nodeValue;
                    debug.trace("URL = " + url);	
                  }
                  catch (err)
                  {
                    url = "www.urbandictionary.com";
                    debug.error(err);
                  }
                }	
                results[z] = {word:word, definition:definition, example:example, url:url};
              }
            }
            catch(err)
            { 
              return 0;
            }
          }
          displayResults();
        }
        else
        {
          noResults.visible = true;
        }
      }
      else
      {
        return 0;
      }
    }
    else
    {
      return 0;
    }
  }
}